package com.ty.xiaoyu.controller;

import com.ty.xiaoyu.XiaoyuApplication;
import com.ty.xiaoyu.entity.*;
import com.ty.xiaoyu.exception.BrowsingHistoryOperationException;
import com.ty.xiaoyu.exception.GreatOperationException;
import com.ty.xiaoyu.exception.UserOperationException;
import com.ty.xiaoyu.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    Logger log = LoggerFactory.getLogger(XiaoyuApplication.class);

    /**
     * 用户登陆
     * @param userName 用户名
     * @param password 用户密码
     * @return token
     */
    @PostMapping("/login")
    private Map<String, Object> login(@RequestParam("userName") String userName,
                                      @RequestParam("password") String password) {
        log.info(MyTimeUtil.nowTime() + "=== login star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        try {
            User user = userService.getUserByUserNameAndPassword(userName, password);
            Map<String, String> payload = new HashMap<>();
            payload.put("userId", user.getUserId());
            payload.put("userName", user.getUserName());
            user.setPassword(null);
            user.setLastLoginTime(MyTimeUtil.nowTime());
            userService.modifyUserLastLog(user);
            // 生成JWT令牌
            String token = JWTUtil.getToken(payload);
            data.put("token", token);
            data.put("user", user);
            modelMap.put("code", 0);
            modelMap.put("msg", "成功");
            modelMap.put("data", data);
        } catch (UserOperationException e) {
            modelMap.put("code", 201);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
        }
        log.info(MyTimeUtil.nowTime() + "=== login end ===");
        return modelMap;
    }

    /**
     * 注销退出
     * @return
     */
    @PostMapping("/logout")
    private Map<String, Object> logout() {
        log.info(MyTimeUtil.nowTime() + "=== logout star ===");
        Map<String, Object> modelMap = new HashMap<>();
        loginUser.setLastLogoutTime(MyTimeUtil.nowTime());
        try {
            userService.modifyUserLastLog(loginUser);
        } catch (UserOperationException e) {
            modelMap.put("code", 204);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== logout 注销失败 ===" + e.getMessage());
            return modelMap;
        }
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", null);
        log.info(MyTimeUtil.nowTime() + "=== logout end ===");
        return modelMap;
    }

    /**
     * 用户注册
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("/register")
    private Map<String, Object> register(@RequestParam("userName") String userName,
                                         @RequestParam("password") String password,
                                         @RequestParam("mail") String mail){
        log.info(MyTimeUtil.nowTime() + "=== register star ===");
        Map<String, Object> modelMap = new HashMap<>();
        User user = new User();
        // 检测用户名是否重复
        try {
            userService.getUserByName(userName);
        } catch (UserOperationException e) {
            modelMap.put("code", 203);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== register 用户名重复 ===" + e.getMessage());
            return modelMap;
        }
        String url = URLUtil.getURL(request);
        String imagePath = url + "/image/default/" + "userImage.png";
        log.debug("imagePath: " + imagePath);
        user.setImagePath(imagePath);
        user.setUserName(userName);
        user.setPassword(password);
        user.setMail(mail);
        try {
            userService.addUser(user);
        } catch (UserOperationException e) {
            modelMap.put("code", 203);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== register 用户创建失败 ===" + e.getMessage());
            return modelMap;
        }
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", null);
        log.info(MyTimeUtil.nowTime() + "=== register end ===");
        return modelMap;
    }

    /**
     * 修改用户信息
     * @param nickname
     * @param image
     * @return
     */
    @PostMapping("/modifyInformation")
    private Map<String, Object> modifyInformation(@RequestParam(value = "nickname", required = false) String nickname,
                                                  @RequestParam(value = "image", required = false) String image) {
        log.info(MyTimeUtil.nowTime() + "=== modifyInformation star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        // 判空
        if ((nickname == null || "".equals(nickname.replace(" ", "")) || "undefined".equals(nickname))
            && (image == null || "".equals(image.replace(" ", "")) || "undefined".equals(image))) {
            modelMap.put("code", 103);
            modelMap.put("msg", "参数全为空");
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== modifyInformation 参数全为空 ===");
            return modelMap;
        }
        User user = userService.getUserById(loginUser.getUserId());
        if (nickname != null && !"".equals(nickname.replace(" ", "")) && !"undefined".equals(nickname)) {
            user.setNickname(nickname);
        }
        if (image != null && !"".equals(image.replace(" ", "")) && !"undefined".equals(image)) {
            // 删除头像
            String oldImageURL = user.getImagePath();
            String oldImagePath = FileUtil.getUserImagePath()
                    + oldImageURL.substring(oldImageURL.lastIndexOf("/") + 1);
            if (!oldImageURL.contains("default")) {
                boolean deleteFileResult = FileUtil.deleteFile(oldImagePath);
                if (!deleteFileResult) {
                    modelMap.put("code", 107);
                    modelMap.put("msg", "原头像删除失败");
                    modelMap.put("data", null);
                    log.error(MyTimeUtil.nowTime() + "=== modifyInformation 原头像删除失败 === oldImagePath: " + oldImagePath);
                    return modelMap;
                }
            }
            // 保存帖子图片
            String filePath = FileUtil.getUserImagePath();
            String fileName = null;
            try {
                fileName = Base64Util.saveImage(image, filePath);
            } catch (IOException e) {
                modelMap.put("code", 301);
                modelMap.put("msg", e.getMessage());
                modelMap.put("data", null);
                log.error(MyTimeUtil.nowTime() + "=== modifyInformation ===" + e.getMessage());
                return modelMap;
            }
            // 获取图片地址（url）
            String url = URLUtil.getURL(request);
            String imagePath = url + "/image/user/" + fileName;
            log.debug("userImagePath: " + imagePath);
            user.setImagePath(imagePath);
        }
        try {
            userService.modifyUser(user);
        } catch (UserOperationException e) {
            modelMap.put("code", 106);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== modifyInformation ===" + e.getMessage());
            return modelMap;
        }
        data.put("user", user);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        log.info(MyTimeUtil.nowTime() + "=== modifyInformation end ===");
        return modelMap;
    }

    /**
     * 获取我的点赞
     * @return
     */
    @GetMapping("/getMyGreat")
    private Map<String, Object> getMyGreat() {
        log.info(MyTimeUtil.nowTime() + "=== getMyGreat star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        List<Great> greatList;
        try {
            greatList = greatService.getGreatListByUserId(loginUser.getUserId());
        } catch (GreatOperationException e) {
            modelMap.put("code", 102);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== getMyGreat ===" + e.getMessage());
            return modelMap;
        }
        for (Great great : greatList) {
            // 获取帖子图片
            Topic topic = great.getTopic();
            List<TopicImage> topicImageList = topicService.getTopicImageList(topic.getTopicId());
            if (topicImageList.size() > 0) {
                topic.setTopicImageList(topicImageList);
            }
            // 获取贴子的回复数量
            topic.setReplyNum(replyService.getReplyNum(topic.getTopicId()));
        }
        data.put("greatList", greatList);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        log.info(MyTimeUtil.nowTime() + "=== getMyGreat end ===");
        return modelMap;
    }

    /**
     * 获取浏览记录
     * @return
     */
    @GetMapping("/getBrowsingHistoryList")
    private Map<String, Object> getBrowsingHistoryList() {
        log.info(MyTimeUtil.nowTime() + "=== getBrowsingHistoryList star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        List<BrowsingHistory> historyList;
        try {
            historyList = browsingHistoryService.getListByUserId(loginUser.getUserId());
        } catch (BrowsingHistoryOperationException e) {
            modelMap.put("code", 102);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== getBrowsingHistoryList ===" + e.getMessage());
            return modelMap;
        }
        for (BrowsingHistory history : historyList) {
            // 获取帖子图片
            Topic topic = history.getTopic();
            List<TopicImage> topicImageList = topicService.getTopicImageList(topic.getTopicId());
            if (topicImageList.size() > 0) {
                topic.setTopicImageList(topicImageList);
            }
            // 获取贴子的回复数量
            topic.setReplyNum(replyService.getReplyNum(topic.getTopicId()));
        }
        data.put("historyList", historyList);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        log.info(MyTimeUtil.nowTime() + "=== getBrowsingHistoryList end ===");
        return modelMap;
    }

    /**
     * 获取我的发布的帖子
     * @return
     */
    @GetMapping("/getMyTopic")
    private Map<String, Object> getMyTopic() {
        log.info(MyTimeUtil.nowTime() + "=== getMyTopic star ===");
        Map<String, Object> modelMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        List<Topic> topicList;
        try {
            topicList = topicService.getTopicListByUserId(loginUser.getUserId());
        } catch (BrowsingHistoryOperationException e) {
            modelMap.put("code", 102);
            modelMap.put("msg", e.getMessage());
            modelMap.put("data", null);
            log.error(MyTimeUtil.nowTime() + "=== getMyTopic ===" + e.getMessage());
            return modelMap;
        }
        for (Topic topic : topicList) {
            // 获取帖子图片
            List<TopicImage> topicImageList = topicService.getTopicImageList(topic.getTopicId());
            if (topicImageList.size() > 0) {
                topic.setTopicImageList(topicImageList);
            }
            // 获取贴子的回复数量
            topic.setReplyNum(replyService.getReplyNum(topic.getTopicId()));
        }
        data.put("topicList", topicList);
        modelMap.put("code", 0);
        modelMap.put("msg", "成功");
        modelMap.put("data", data);
        log.info(MyTimeUtil.nowTime() + "=== getMyTopic end ===");
        return modelMap;
    }


}
